<template>
  <div class="page-container">
    <!-- 头部 -->
    <!-- <div class="page-title">
      <div class="flexTitle">
        <div class="mxName">模型名称</div>
        <div class="mxDescription">
          <h3>围标串标xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
          <div style="margin-top: 20px">
            <span>模型类型：工程建设-招标投标</span>
            <span>问题运行时间: 2025-10-11</span>
            <span>创建人: 2025-10-11</span>
          </div>
        </div>
      </div>
      <div class="wtsl">
        <img src="@/assets/imgs/wtsl.svg" alt="" />
        <h3>问题数量：<span>3</span></h3>
      </div>
    </div> -->
    <!-- 表格 -->
    <div class="table-container">
      <!-- <el-radio-group v-model="tabPosition" style="margin-bottom: 10px; margin-top: 20px">
        <el-radio-button value="待办理">待办理</el-radio-button>
        <el-radio-button value="已办理">已办理</el-radio-button>
      </el-radio-group> -->
      <!-- 搜索区域 -->
      <el-form
        class="mt-[29px] pl-[20px]"
        label-position="right"
        label-width="auto"
        :model="searchForm"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="企业名称：">
              <el-input placeholder="请输入" v-model="searchForm.qyName" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="项目名称：">
              <el-input placeholder="请输入" v-model="searchForm.xmName" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="">
              <div @click="getYJData" class="dp-risk-btn ml-[31px] mr-[8px] cursor-pointer"
                >查询</div
              >
              <div @click="resetFn" class="dp-risk-btn cursor-pointer">重置</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        class="spaced-table"
        :row-class-name="tableRowClassName"
        :data="tableData"
        show-overflow-tooltip
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column width="80px" type="index" label="序号" />
        <div class="bg-red-600" style="height: 20px; width: 20px"></div>
        <el-table-column
          min-width="180"
          v-for="item in tableColumnJD_DBL"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
        />

        <el-table-column fixed="right" label="操作" min-width="180">
          <template #default="scope">
            <el-button style="color: #1fc6ff" link @click.prevent="blClick(scope.row)">
              办理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
  <!-- 办理弹窗 -->
  <el-dialog ref="dialogBanLiRef" title="办理" width="912px" height="523px" v-model="dialogVisible">
    <div class="flex pl-[14px] flex flex-col items-center h-[416px]">
      <el-form
        ref="formRef"
        style="max-width: 600px"
        :model="ValidateForm"
        label-width="auto"
        class="demo-ruleForm flex-1"
      >
        <el-form-item label="办理方式：">
          <el-select
            v-model="ValidateForm.type"
            placeholder="please select your zone"
            style="width: 684px; height: 40px"
          >
            <el-option label="转办" value="1" />
            <el-option label="拟自办" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item
          label="办理单位："
          :rules="[{ required: true, message: '请选择办理单位' }]"
          v-if="ValidateForm.type === '1'"
        >
          <el-cascader
            style="width: 684px; height: 40px"
            v-model="ValidateForm.banliDW"
            :options="options"
            :props="casderProps"
            @change="getUserList"
          />
        </el-form-item>
        <el-form-item label="办理人：" prop="banliR" v-if="ValidateForm.type === '1'">
          <el-select
            v-model="ValidateForm.banliR"
            placeholder="请选择办理人"
            style="width: 684px; height: 40px"
          >
            <el-option
              v-for="item in userList"
              :key="item.value"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="办理建议："
          prop="banliJZ"
          :rules="[{ required: true, message: '请填写办理建议' }]"
          v-if="ValidateForm.type === '1'"
        >
          <el-input
            v-model="ValidateForm.banliJZ"
            style="width: 684px; background-color: #093a51"
            :rows="2"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="核查状态：" v-if="ValidateForm.type === '2'">
          <el-select
            v-model="ValidateForm.hczt"
            placeholder="请选择核查状态"
            style="width: 684px; height: 40px"
          >
            <el-option label="查实" value="1" />
            <el-option label="查否" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="处理情况："
          prop="clqk"
          :rules="[{ required: true, message: '请填写处理情况' }]"
          v-if="ValidateForm.type === '2'"
        >
          <el-input
            v-model="ValidateForm.clqk"
            style="width: 684px; background-color: #093a51"
            :rows="2"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item
          label="上传附件："
          prop="fjsc"
          :rules="[{ required: false, message: '请填写处理情况' }]"
          v-if="ValidateForm.type === '2'"
        >
          <el-upload
            v-model:file-list="fileList"
            class="uploadBox"
            :action="uploadUrl"
            :http-request="httpRequest"
            multiple
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-success="handleFileSuccess"
            :limit="3"
            :on-exceed="handleExceed"
            :show-file-list="false"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip"
                >支持上传.rar .zip .doc .docx .pdf .jpgg 文件大小50MB以下</div
              >
              <div class="flexListBox">
                <li v-for="item in uploadList" class="file-item" :key="item.uid">
                  <div class="file-name">{{ item.name }}</div>
                  <el-button type="primary" @click="DeleteFilled(item.uid)">删除</el-button>
                </li>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <div class="flex justify-center items-center mt-aut mb-[45px]">
        <el-button @click="submitForm(formRef)" type="primary">确定</el-button>
        <el-button @click="resetForm(formRef)">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script lang="ts" setup>
import { getUserProfile, ProfileVO } from '@/api/system/user/profile'
import * as FileApi from '@/api/infra/file'

import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { log } from 'console'
import { useRoute } from 'vue-router'
import router from '@/router'
const uploadUrl = import.meta.env.VITE_BASE_URL + 'admin-api/infra/file/upload'

const message = useMessage() // 消息弹窗
const route = useRoute()
const options = ref([])
const formRef = ref()
const { t } = useI18n()
const tabPosition = ref('待办理')
const searchForm = reactive({
  qyName: '',
  xmName: ''
})
// 获取tableid
const tableId = ref('')
const tableData = ref()
const tableColumnJD_DBL = ref()
const tableColumnJD_DBL_REF = ref()
const columnNameMapData = ref()
const getTableId = async () => {
  if (route.query.id) {
    ProcessInstanceApi.getProcessInstanceBpmnModelView(route.query.id).then((res) => {
      tableId.value = res.processInstance.businessKey
      ProcessInstanceApi.getTableList(res.processInstance.businessKey).then((res) => {
        if (res.length) {
          const columns = JSON.parse(res[0].params).columnName
          columnNameMapData.value = columns
          let datas = res.map((item) => {
            let jb = JSON.parse(item.params)
            jb.queryParams.id = item.id
            return jb.queryParams
          })
          tableData.value = datas
          let NullArr = []
          if (columns) {
            let listItemKey = []
            if (columns && columns.length > 0) {
              listItemKey = Object.keys(columns[0])
            }
            Object.keys(columns).forEach((key) => {
              if (listItemKey.length > 0) {
                if (listItemKey.includes(key)) {
                  NullArr.push({
                    label: columns[key],
                    prop: key
                  })
                }
              } else {
                NullArr.push({
                  label: columns[key],
                  prop: key
                })
              }
            })
            tableColumnJD_DBL.value = NullArr
            tableColumnJD_DBL_REF.value = NullArr.map((item) => item.label)
          } else {
            tableColumnJD_DBL.value = []
            tableColumnJD_DBL_REF.value = []
          }
          console.log('table列表1', tableColumnJD_DBL)
          console.log('table列表2', tableColumnJD_DBL_REF)
        } else {
          router.push('/bpm/task/todo')
        }
      })
    })
  }
}
const tableRowClassName = ({ row, rowIndex }) => {
  rowIndex === 0 ? 'first-row' : ''
  if (rowIndex % 2 === 0) {
    return 'success-row'
  } else {
    return 'warning-row'
  }
}
// 查询
const getYJData = () => {}
// 重置
const resetFn = () => {}
// 办理
const blId = ref()
const blClick = (row) => {
  console.log('打开办理', row)
  uploadList.value = []
  blId.value = row.id
  opneBanLi(row, columnNameMapData.value)
  dialogVisible.value = true
}
const userInfo = ref()
const getUserInfo = async () => {
  const users = await getUserProfile()
  userInfo.value = users
  console.log('userInfo.value', userInfo.value)
}
// 查看详情
const viewDetail = () => {}
// 办理弹窗
const dialogVisible = ref(false)
const ValidateForm = reactive({
  type: '1',
  banliDW: '',
  chaosongSW: '',
  banliJZ: '',
  clqk: '',
  hczt: '',
  fjsc: []
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      ProcessInstanceApi.getAppro(ArrpoId.value).then((res1) => {
        if (res1.activityNodes.length) {
          let su = {}

          res1.activityNodes.forEach((item) => {
            if (item.nodeType == 11) {
              su[item.id] = [Number(ValidateForm.banliR)]
            }
          })
          var jsonObj = [
            JSON.stringify({ queryParams: tableRow.value, columnName: columnNameMap.value })
          ]
          const params = {
            resultTable: tableName.value, //表明
            paramsJson: jsonObj, //参数
            fqrId: userInfo.value?.id, //发起人id
            bllx: ValidateForm.type, // 办理类型
            jsrDw: selectUnitid.value, // 处理人单位
            jsrId: ValidateForm.banliR, //处理人id
            blyj: ValidateForm.banliJZ, //办理意见
            startUserSelectAssignees: su, //是否发起人自选处理人
            bpmId: tableId.value,
            ids: [blId.value],
            // 自办参数
            hczt: ValidateForm.hczt, //核查状态
            clqk: ValidateForm.clqk //处理情况
          }
          if (ValidateForm.type == '2') {
            params.jsrId = userInfo.value?.id
            params.jsrDw = userInfo.value?.dept?.id
            params.blyj = '自办'
            params.fjsc = JSON.stringify(uploadList.value)
          }
          ProcessInstanceApi.bpmCreate(params).then((res) => {
            if (res) {
              message.success('办理成功')
              getTableId()
              dialogVisible.value = false
            }
            console.log('创建成功', res)
          })
        }
      })
    } else {
      console.log('error submit!')
    }
  })
}
const casderProps = {
  lazy: true,
  label: 'name',
  value: 'id',
  checkStrictly: true,
  multiple: false, //支持多选
  lazyLoad(node, resolve) {
    if (node.level == 0) {
      setTimeout(() => {
        ProcessInstanceApi.getUnit(0).then((res) => {
          console.log('数据-0---', res)

          if (res) {
            const nodes = res.map((item) => ({
              ...item,
              label: item.name,
              value: item.id,
              leaf: node.level >= 2 //叶子节点最多有三级
            }))
            resolve(nodes)
          }
        })
      }, 1000)
    } else {
      const { level } = node
      setTimeout(() => {
        ProcessInstanceApi.getUnit(node.value).then((res) => {
          if (res) {
            const nodes = res.map((item) => ({
              ...item,
              label: item.name,
              value: item.id,
              leaf: node.level >= 2 //叶子节点最多有三级
            }))
            resolve(nodes)
          }
        })
      }, 1000)
    }
  }
}
// 根据单位id查询人列表
const userList = ref([])
const selectUnitid = ref()
const getUserList = (row) => {
  const unitid = row[row.length - 1]
  selectUnitid.value = unitid
  nextTick(() => {
    ProcessInstanceApi.getUser(unitid).then((res) => {
      if (res) {
        userList.value = res
      }
    })
  })
}
const ArrpoId = ref()
const getKeyS = () => {
  ProcessInstanceApi.getKey('WTBL').then((res) => {
    ArrpoId.value = res.id
  })
}
const dialogBanLiRef = ref(null)
const columnNameMap = ref()
const tableRow = ref()
const tableName = ref('')
const opneBanLi = (row, column) => {
  tableName.value = row.tableName
  getKeyS()
  columnNameMap.value = column
  tableRow.value = row
  console.log('columnNameMap', columnNameMap.value)
  console.log('tableRow', tableRow.value)
}
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  dialogVisible.value = false
}
const handleSelectionChange = () => {}
// 上传附件
const handlePreview = () => {}
const beforeRemove = () => {}
const handleExceed = () => {}
const fileList = ref([])
// 文件上传之前判断
const beforeUpload = (UploadRawFile) => {
  // if (fileList.value.length >= props.limit) {
  //   message.error(`上传文件数量不能超过${props.limit}个!`);
  //   return false;
  // }
  // let fileExtension = ''
  // if (file.name.lastIndexOf('.') > -1) {
  //   fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
  // }
  // const isImg = props.fileType.some((type: string) => {
  //   if (file.type.indexOf(type) > -1) return true
  //   return !!(fileExtension && fileExtension.indexOf(type) > -1)
  // })
  // const isLimit = file.size < 50 * 1024 * 1024;
  // if (!isImg) {
  //   message.error(`文件格式不正确, 请上传${props.fileType.join('/')}格式!`)
  //   return false
  // }
  // if (!isLimit) {
  //   message.error(`上传文件大小不能超过${50}MB!`);
  //   return false;
  // }
  // message.success('正在上传文件，请稍候...');
}
// 文件上传成功
const uploadList = ref([])
const handleFileSuccess = (res, response) => {
  message.success('上传成功')
  // console.log('上传成功', res, response);
  if (res.code == 0) {
    uploadList.value.push({
      name: response.name,
      url: res.data,
      uid: response.uid
    })
  }

  // 删除自身
  // const index = fileList.value.findIndex(item => item.response?.data === res.data);
  // fileList.value.splice(index, 1);
  // uploadList.value.push({ name: res.data, url: res.data });
}
const DeleteFilled = (id) => {
  const newFileList = uploadList.value.filter((item) => item.uid !== id)
  console.log('删除后', newFileList)
  uploadList.value = newFileList
}
// 删除上传文件
const handleRemove = (file) => {
  const index = fileList.value.map((f) => f.name).indexOf(file.name)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
}
const httpRequest = async (options) => {
  // 模式二：后端上传
  // 重写 el-upload httpRequest 文件上传成功会走成功的钩子，失败走失败的钩子
  return new Promise((resolve, reject) => {
    FileApi.updateFile({ file: options.file })
      .then((res) => {
        if (res.code === 0) {
          resolve(res)
        } else {
          reject(res)
        }
      })
      .catch((res) => {
        reject(res)
      })
  })
}
onMounted(() => {
  getTableId()
  getUserInfo() //获取用户信息
})
</script>
<style lang="scss" scoped>
.page-container {
  width: 100%;
  height: 100%;
  padding: 20px;
  border: 1px solid #0b3261;
  .page-title {
    width: 100%;
    height: 8.3854vw;
    border-bottom: 1px dashed gray;
    position: relative;
    .flexTitle {
      display: flex;
      .mxName {
        width: 97px;
        height: 39px;
        line-height: 39px;
        background: #021330;
        border-color: #158ab9;
        border-radius: 5px;
        margin-right: 14px;
        color: #ffff;
        text-align: center;
      }
      .mxDescription {
        span {
          margin-right: 64px;
        }
      }
    }

    .wtsl {
      position: absolute;
      right: 20px;
      top: 10px;
      display: flex;
      align-items: center;
    }
  }
  .table-container {
    width: 100%;
    height: 37.8646vw;
  }
}
// :deep(.el-table__row) {
//   // 悬停效果
//   &:hover > td {
//     background-color: #0d5777 !important;
//   }
// }
.uploadBox {
  height: 150px;
  overflow-y: auto;
  width: 100%;
  .flexListBox {
    color: #fff;
    li {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      margin-bottom: 5px;
      border-bottom: 1px solid #817e7eb4;
    }
  }
}
/* 定义滚动条的整体样式 */
.uploadBox ::-webkit-scrollbar {
  width: 5px; /* 对于垂直滚动条 */
  height: 16px; /* 对于水平滚动条 */
  background-color: #042a41; /* 滚动条的背景色 */
}

/* 定义滚动条轨道的样式 */
.uploadBox ::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); /* 轨道的阴影 */
  border-radius: 5px; /* 轨道的圆角 */
  background-color: #042a41; /* 轨道的背景色 */
}

/* 定义滑块的样式 */
.uploadBox ::-webkit-scrollbar-thumb {
  border-radius: 5px; /* 滑块的圆角 */
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3); /* 滑块的阴影 */
  background-color: #555; /* 滑块的背景色 */
}
</style>
